package com.kuang.exam.modules.sys.lesson.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.kuang.exam.core.api.ApiRest;
import com.kuang.exam.core.api.controller.BaseController;
import com.kuang.exam.core.api.dto.BaseIdsReqDTO;
import com.kuang.exam.core.api.dto.PagingReqDTO;
import com.kuang.exam.core.utils.BeanMapper;
import com.kuang.exam.core.utils.excel.ExportExcel;
import com.kuang.exam.core.utils.excel.ImportExcel;
import com.kuang.exam.modules.qu.dto.export.QuExportDTO;
import com.kuang.exam.modules.qu.dto.request.QuQueryReqDTO;
import com.kuang.exam.modules.sys.lesson.dto.export.LessonExportDTO;
import com.kuang.exam.modules.sys.lesson.dto.request.StudQueryDTO;
import com.kuang.exam.modules.sys.lesson.dto.SysLessonDTO;
import com.kuang.exam.modules.sys.lesson.entity.SysLesson;
import com.kuang.exam.modules.sys.lesson.entity.SysUserLesson;
import com.kuang.exam.modules.sys.lesson.service.SysLessonService;
import com.kuang.exam.modules.sys.lesson.service.SysUserLessonService;
import com.kuang.exam.modules.sys.lesson.dto.response.SysStudentDTO;
import com.kuang.exam.modules.sys.lesson.dto.response.SysTeacherDTO;
import com.kuang.exam.modules.sys.user.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 管理课程控制器
 * </p>
 */
@Api(tags = {"管理课程"})
@RestController
@RequestMapping("/exam/api/sys/lesson")
public class SysLessonController extends BaseController {

    @Autowired
    private SysLessonService baseService;

    @Autowired
    private SysUserLessonService userLessonService;

    @Autowired
    private SysUserService userService;

    /**
     * 保存或修改系统用户
     *
     * @return
     */
    @ApiOperation(value = "保存或修改")
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public ApiRest save(@RequestBody SysLessonDTO reqDTO) {
        baseService.save(reqDTO);
        return success();
    }


    /**
     * 批量删除
     *
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "批量删除")
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public ApiRest delete(@RequestBody BaseIdsReqDTO reqDTO) {

        //根据ID删除
        baseService.removeByIds(reqDTO.getIds());
        //同步删除sys_user_lesson表
        userLessonService.removeByLessonId(reqDTO.getIds());
        return super.success();
    }

    /**
     * 单个删除
     *
     * @return
     */
    @ApiOperation(value = "单个删除")
    @RequestMapping(value = "/deleteOne", method = {RequestMethod.POST})
    public ApiRest deleteOne(@RequestBody SysLessonDTO lessonDTO) {
        String lessonId = lessonDTO.getId();
        //根据ID删除
        baseService.removeById(lessonId);
        //同步删除sys_user_lesson表
        QueryWrapper<SysUserLesson> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysUserLesson::getLessonId, lessonId);
        userLessonService.remove(wrapper);
        return super.success();
    }

    /**
     * 分页查找
     *
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "分页查找")
    @RequestMapping(value = "/paging", method = {RequestMethod.POST})
    public ApiRest<IPage<SysLessonDTO>> paging(@RequestBody PagingReqDTO<SysLessonDTO> reqDTO) {

        //分页查询并转换
        IPage<SysLessonDTO> page = baseService.paging(reqDTO);
        return super.success(page);
    }

    /**
     * 查找列表，每次最多返回200条数据
     *
     * @return
     */
    @ApiOperation(value = "查找列表")
    @RequestMapping(value = "/list", method = {RequestMethod.POST})
    public ApiRest<List<SysLessonDTO>> list() {

        //分页查询并转换
        QueryWrapper<SysLesson> wrapper = new QueryWrapper<>();

        //转换并返回
        List<SysLesson> list = baseService.list(wrapper);

        //转换数据
        List<SysLessonDTO> dtoList = BeanMapper.mapList(list, SysLessonDTO.class);

        return super.success(dtoList);
    }

    @ApiOperation(value = "查找老师列表")
    @RequestMapping(value = "/teacherList", method = {RequestMethod.POST})
    public ApiRest<List<SysTeacherDTO>> teacherList() {
        return super.success(userService.listTeachers());
    }

    @ApiOperation(value = "查找学生列表")
    @RequestMapping(value = "/studentList", method = {RequestMethod.POST})
    public ApiRest<List<SysStudentDTO>> studentList(@RequestBody StudQueryDTO reqDTO) {
        return super.success(userService.listStudents(reqDTO));
    }


    /**
     * 下载导入课程数据模板
     */
    @ResponseBody
    @RequestMapping(value = "import/template")
    public ApiRest importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "课程导入模板.xlsx";
            List<LessonExportDTO> templateList = Lists.newArrayList();

            LessonExportDTO l1 = new LessonExportDTO();
            l1.setName("正式导入，请删除此说明行");
            l1.setLessonType("填0，1；0表示选修，1表示必修");
            l1.setLessonPeriod("48");
            l1.setTeachers(Collections.singletonList("已存在老师的用户名（或唯一工号），多个用英文逗号隔开，老师名错误无法导入"));

            LessonExportDTO lessonExportDTO = new LessonExportDTO();
            lessonExportDTO.setName("计算机专业英语");
            lessonExportDTO.setLessonType("1");
            lessonExportDTO.setLessonPeriod("48");
            lessonExportDTO.setTeachers(Arrays.asList("wlz", "zpp"));

            templateList.add(l1);
            templateList.add(lessonExportDTO);
            new ExportExcel("课程导入模板", LessonExportDTO.class, 1).setDataList(templateList).write(response, fileName).dispose();
            return super.success();
        } catch (Exception e) {
            return super.failure("导入模板下载失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequestMapping(value = "/export")
    public ApiRest exportFile(HttpServletResponse response, @RequestBody SysLessonDTO reqDTO) {

        // 导出文件名
        String fileName = "导出的课程-" + System.currentTimeMillis() + ".xlsx";

        try {
            List<LessonExportDTO> list = baseService.listforExport(reqDTO);
            new ExportExcel("课程", LessonExportDTO.class).setDataList(list).write(response, fileName).dispose();
            return super.success();
        } catch (Exception e) {
            return failure("导出失败，原因：" + e.getMessage());
        }
    }

    /**
     * 导入Excel
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/import")
    public ApiRest importFile(@RequestParam("file") MultipartFile file) {

        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<LessonExportDTO> list = ei.getDataList(LessonExportDTO.class);

            // 导入数据条数
            baseService.importExcel(list);

            // 导入成功
            return super.success();
        } catch (IOException | InstantiationException | IllegalAccessException | InvalidFormatException e) {
            return failure("导入失败，原因：" + e.getMessage());
        }


    }
}
